<?php
/**
 * Adapter to use Smarty library as templating engine
 *
 * @category     Shuxun Cms
 * @date         2015年9月18日
 * @author       Shuxun Team <kaiping.jiang@scshux.com>
 * @file         Smarty.php
 */
namespace Scshux\Mvc\View\Engine;
use Phalcon\DiInterface;
use Phalcon\Mvc\View\Engine;
use Phalcon\Mvc\View\EngineInterface;
use Phalcon\Mvc\ViewBaseInterface;
use Phalcon\Di\FactoryDefault;
use Scshux\Tag\SmartyTag;
use Scshux\Tag\SmartyBlock;
use Scshux\Tag\SmartyModifier;
class Smarty extends Engine implements EngineInterface
{
	/**
	 * @var \Smarty
	 */
	protected $smarty;

	/**
	 * {@inheritdoc}
	 *
	 * @param ViewBaseInterface $view
	 * @param DiInterface       $di
	 */

	public function __construct(ViewBaseInterface $view, DiInterface $di = null)
	{
		parent::__construct($view, $di);
	}

	/**
	 * {@inheritdoc}
	 *
	 * @param string  $path
	 * @param array   $params
	 * @param boolean $mustClean
	 */
	public function render($path, $params, $mustClean = false)
	{


		$this->smarty->setTemplateDir($this->view->getViewsDir());
		if (!isset($params['content'])) {
			$params['content'] = $this->_view->getContent();
		}

		foreach ($params as $key => $value) {
			if ($params['_' . $key] === true) {
				$this->smarty->assign($key, $value, true);
			} else {
				$this->smarty->assign($key, $value);
			}
		}

		$content = $this->smarty->fetch($path);
		if ($mustClean) {
			$this->_view->setContent($content);
		} else {
			echo $content;
		}
	}
	/**
	 * Set Smarty's options
	 *
	 * @param array $options
	 */
	public function setOptions(array $options)
	{
		foreach ($options as $k => $v) {
			$this->smarty->$k = $v;
		}
	}

	/**
	 * 设置smarty对象
	 * @param \Smarty $smarty
	 */
	public  function setSmarty($smarty)
	{
		/**
		 * 注册函数
		 */
		$smartyTag = new SmartyTag();
		$functions = get_class_methods($smartyTag);
		foreach ($functions as $function){
			$smarty->registerPlugin('function', $function, '\Scshux\Tag\SmartyTag::'.$function);
		}

        /**
         * 注册块
         */
		$smartyBlock = new SmartyBlock();
		$blocks = get_class_methods($smartyBlock);
		foreach ($blocks as $block)
		{
			$smarty->registerPlugin('block', $block, '\Scshux\Tag\SmartyBlock::'.$block);
		}

		/**
		 * 注册修饰符
		 */
		$smartyModifier = new SmartyModifier();
		$modifiers = get_class_methods($smartyModifier);
		foreach ($modifiers as $modifier)
		{
			$smarty->registerPlugin('modifier', $modifier, '\Scshux\Tag\SmartyModifier::'.$modifier);
		}


		$this->smarty = $smarty;
	}

	/**
	 * Get Smarty object
	 *
	 * @return \Smarty
	 */
	public function getSmarty()
	{
		return $this->smarty;
	}
}